package com.openspring.platform.dao.impl;

import java.util.List;
import org.springframework.stereotype.Repository;
import com.openspring.framework.dao.AbstractSpringGenericDAO;
import com.openspring.framework.extend.spring.EntityPropertyRowMapper;
import com.openspring.platform.dao.DeptDAO;
import com.openspring.platform.model.Dept;

@Repository("deptDAO")
public class DeptDAOImpl extends AbstractSpringGenericDAO<Dept, Long> implements DeptDAO {

	@Override
	public List<Dept> queryAllChildren(Long id) {
		String sql = "WITH RECURSIVE r AS (" +
				"SELECT * FROM emp.t_platform_dept \"parentId\" = ? UNION ALL " +
				"SELECT t.* FROM emp.t_platform_dept t, r WHERE t.\"parentId\" = r.id)" +
				"SELECT * FROM r ORDER BY r.sort";
		return getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Dept>(Dept.class), id);
	}
	
	@Override
	public List<Dept> queryChildren(Long id) {
		String sql = "SELECT * FROM emp.t_platform_dept WHERE \"parentId\" = ? ORDER BY sort";
		return getJdbcTemplate().query(sql, new EntityPropertyRowMapper<Dept>(Dept.class), id);
	}
	
	@Override
	public boolean isExistChindren(Long id) {
		String sql = "SELECT COUNT(id) FROM t_platform_dept WHERE \"parentId\" = ?";
		return getJdbcTemplate().queryForInt(sql, id) > 0;
	}
}
